package com.kuaiying.kuai.ying.controller.user;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;



import java.net.HttpURLConnection;
import java.net.URL;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.jfinal.aop.Before;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;
import com.kuaiying.kuai.ying.model.leaflet.LeafletModel;
import com.kuaiying.kuai.ying.model.print_file.PrintfileModel;
import com.kuaiying.kuai.ying.model.task_id.TaskidModel;
import com.kuaiying.kuai.ying.model.print_shop.PrintshopModel;
import com.kuaiying.kuai.ying.model.user.UserModel;
import com.kuaiying.kuai.ying.validator.HomeValidator;
import com.kuaiying.kuai.ying.validator.LoginValidator;
import com.kuaiying.kuai.ying.validator.RegistValidator;
import com.kuaiying.kuai.ying.validator.UploadValidator;
import com.kuaiying.kuai.ying.model.shop.ShopModel;
import com.kuaiying.kuai.ying.model.sign.SignModel;
import com.kuaiying.kuai.ying.model.yangzhengma.YangzhengmaModel;

import java.text.SimpleDateFormat; 
import java.util.Date;

import com.kuaiying.kuai.ying.model.school.SchoolModel;
import java.text.ParseException;


public class UserController extends Controller{

	public void index(){
		String uName = getSessionAttr("user_phonenumber");
		if( uName != null ){
			redirect("/user/home");
			return;
		}
		render("login.html");
	}
	
	public void login(){
		String uName = getSessionAttr("user_phonenumber");
		if( uName != null ){
			System.out.println( "has user_phonenumber :" + uName );
			redirect("/user/print");
			return;
		}
		render("login.html");
	}
	
	@Before( LoginValidator.class )
	public void loginPost(){
		
		String phonenumber = getPara("phonenumber");
    	String pwd = getPara("password");
    	UserModel user = UserModel.me.getUserByNameAndPwd(phonenumber, pwd);
    	
    	if (user != null){
            String bbsID = phonenumber + pwd;
            setCookie("bbsID", bbsID, 3600*24*30);
            setSessionAttr("user_phonenumber", phonenumber);
            setSessionAttr("userID", user.get("user_id"));
            Integer user_id = user.get("user_id");
            //修改用户登录时间
            UserModel.me.upadteUser_lastlogintime(user_id);
//            System.out.println( user.get("user_id") );
            //redirect("/user/home");
            //redirect("/user/print");
            
            //获取所以打印店
            redirect("/user/print");
            
            //List<PrintshopModel> printshopList = PrintshopModel.me.getAllprintshop();
            //setAttr("printshopList", printshopList);
            //render("print.html");
        }else{
            setAttr("loginError", "用户名或密码错误");
            render("login.html");
        }
	}
	
	public void register(){
		String phonenumber = getSessionAttr("user_phonenumber");

		if( phonenumber != null ){
			System.out.println( "has user_phonenumber :" + phonenumber );
			redirect("/user/print");
			return;
		}
		List<SchoolModel> schools = SchoolModel.me.getSchool();
		setAttr("schools", schools);
		setAttr("user_phonenumber", "");
		render("register.html");
	}
	
	   public static String get(String urlAll,String charset){
		   BufferedReader reader = null;
		   String result = null;
		   StringBuffer sbf = new StringBuffer();
		   String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";//模拟浏览器
		   try {
			   URL url = new URL(urlAll);
			   HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			   connection.setRequestMethod("GET");
			   connection.setReadTimeout(30000);
			   connection.setConnectTimeout(30000);
			   connection.setRequestProperty("User-agent",userAgent);
			   connection.connect();
			   InputStream is = connection.getInputStream();
			   reader = new BufferedReader(new InputStreamReader(
						is, charset));
				String strRead = null;
				while ((strRead = reader.readLine()) != null) {
					sbf.append(strRead);
					sbf.append("\r\n");
				}
				reader.close();
				result = sbf.toString();
			   
		} catch (Exception e) {
			e.printStackTrace();
		}
		   return result;
	   }
	
		public void Vcode(){
			String phonenumber = getPara("mobile");
			System.out.println("===============");
			System.out.println(phonenumber);
			System.out.println("===============");
			if( phonenumber != null ){
				if( phonenumber.length() == 11 ){
					//生成随机数
					Integer x1=(int)(Math.random()*9);
					Integer x2=(int)(Math.random()*9);
					Integer x3=(int)(Math.random()*9);
					Integer x4=(int)(Math.random()*9);
					String yangzheng = x1.toString()+x2.toString()+x3.toString()+x4.toString();
					System.out.println(yangzheng);
					//发送短信
					String city = "suzhou";//参数
					String url = "http://v.juhe.cn/sms/send?mobile="+phonenumber+"&tpl_id=5685&tpl_value=%23code%23%3D"+yangzheng+"&key=5d53a4e1cbb182f03b7ab57b8ddcfb7f";//url为请求的api接口地址
					String charset ="UTF-8";
					String jsonResult = get(url, charset);
					//System.out.println(jsonResult);
					
					//验证码存入数据库
					YangzhengmaModel yangzhengmaModel = YangzhengmaModel.me.findByPN(phonenumber);
					int flag = 0;
					if(yangzhengmaModel == null){
						flag = 1;
					    yangzhengmaModel = new YangzhengmaModel();
					}
					yangzhengmaModel.set("phonenum", phonenumber);
					yangzhengmaModel.set("vcode",yangzheng);
					String now_time = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss").format( new Date());
					yangzhengmaModel.set("time",now_time);
					if(flag == 1){
						yangzhengmaModel.save();
					}
					else {
						yangzhengmaModel.update();
					}
					
					List<SchoolModel> schools = SchoolModel.me.getSchool();
					setAttr("schools", schools);
					setAttr("phonenumber", phonenumber);
					render("register.html");
				}
			}
		}	   
		
	//@Before( RegistValidator.class )
	public void registerPost(){
		
		String userName = getPara("username");
		String mobile = getPara("mobile");
		
		String password = getPara("password");
		String repassword = getPara("repassword");
		String school_id = getPara("school");
		
		String yanzhengma = getPara("yanzhengma");
        //获取电话号码对应的验证码和时间
		YangzhengmaModel yanzhengmaModel = YangzhengmaModel.me.findByPN(mobile);
		if (UserModel.me.getUserByPhoneNumber(mobile)) {
			this.renderText( "号码已注册"  );
			return;
		}
		if(yanzhengmaModel == null){
			redirect("/user/register");
		}

		if(yanzhengma.equals(yanzhengmaModel.getStr("vcode"))) {
			Integer gold = 30;
			Integer use_gold = 0;
			//UserModel.me.saveUserByName_Pwd_Mobile_School(userName,password,mobile,school);
			System.out.println( UserModel.me.saveUserByName_Pwd_Mobile_School(userName,password,mobile,school_id,gold,use_gold) );
			render("login.html");
		} else {
			redirect("/user/register");
		}		
	}
	
	public void unpdataPost(){
		Integer user_id = getSessionAttr("userID");
		String userName = getPara("truename");
		String email = getPara("email");
		String major = getPara("major");
		//String password = getPara("password");
		String grade = getPara("grade");
		String beizhu_str = getPara("intro");
		String sex_str = getPara("sex");
		String beizhu = getPara("intro");
		String school = getPara("school");
		//UserModel.me.saveUserByName_Pwd_Mobile_School(userName,password,mobile,school);
		//System.out.println( UserModel.me.upadteUser(user_id,userName,email,grade,major,beizhu_str,sex_str) );
		UserModel user = new UserModel();
		user.set("user_id", user_id);
		user.set("email", email);
		user.set("grade", grade);
		user.set("major", major);
		user.set("beizhu_new", beizhu_str);
		user.set("sex", sex_str);
		user.set("school", school);
		//System.out.println(user);
		//return true;
		user.update();
		redirect("/user/print");
	}
	
	@Before( HomeValidator.class )
	public void home(){
		render("home.html");
	}
	
	public void billing(){
		Integer user_id = getSessionAttr("userID");
		if( user_id != null ){
    		Integer pageNumber = 1;
    		Integer pagevalue = 10;
    		try{
    			pageNumber = Integer.valueOf(getPara("page"));
    		}
    		catch (Exception e){
    			pageNumber = 1;
    		}
    		setAttr("nav_url", "/user/billing");
			UserModel userModel = UserModel.me.findById(user_id);
			setAttr("userModel", userModel);
			
        	List<TaskidModel> tasklist_tmp = TaskidModel.me.getAllTask_user(user_id);
    		Integer totlenum = tasklist_tmp.size();	//分页测试
            Integer totel_page = 1;
            if( totlenum%pagevalue == 0 ){
            	totel_page = (totlenum-totlenum%pagevalue)/pagevalue;
            }else{
            	totel_page = (totlenum-totlenum%pagevalue)/pagevalue+1;
            }
            List<TaskidModel> tasklist = TaskidModel.me.getAllTask_user_page(user_id,pageNumber);
            setAttr("tasks", tasklist);
            setAttr("pageNumber", pageNumber);
            setAttr("totalPage", totel_page);
            setAttr("totalRow", totlenum);
            
			render("billing.html");
		}
	}
	
	public void print(){
        Integer user_id = getSessionAttr("userID");

        //修改用户登录时间
        if( user_id != null ){
            //获取所以打印店
            List<PrintshopModel> printshopList = PrintshopModel.me.getAllprintshop();
            setAttr("printshopList", printshopList);
            render("print.html");
        }
	}
	
	public void order(){
        Integer user_id = getSessionAttr("userID");
        System.out.println("===============");
        System.out.println(user_id);
        System.out.println("===============");
        //修改用户登录时间
        if( user_id != null ){
            //获取所以打印店
        	//System.out.println("====1====");
        	//List<TaskidModel> tasklist = TaskidModel.me.getAllTask_user(user_id);
            //setAttr("tasks", tasklist);
            //render("order.html");
    		Integer pageNumber = 1;
    		Integer pagevalue = 10;
    		try{
    			pageNumber = Integer.valueOf(getPara("page"));
    		}
    		catch (Exception e){
    			pageNumber = 1;
    		}
    		setAttr("nav_url", "/user/order");
    		List<TaskidModel> tasklist_tmp = TaskidModel.me.getAllTask_user(user_id);
    		Integer totlenum = tasklist_tmp.size();	//分页测试
            Integer totel_page = 1;
            if( totlenum%pagevalue == 0 ){
            	totel_page = (totlenum-totlenum%pagevalue)/pagevalue;
            }else{
            	totel_page = (totlenum-totlenum%pagevalue)/pagevalue+1;
            }
            List<TaskidModel> list_page = TaskidModel.me.getAllTask_user_page(user_id,pageNumber);
            setAttr("tasks", list_page);
            setAttr("pageNumber", pageNumber);
            setAttr("totalPage", totel_page);
            setAttr("totalRow", totlenum);
    		render("order.html");
        }
        else {
        	redirect("/user/index");
        }
        
	}
	
	public void info(){
		Integer user_id = getSessionAttr("userID");
		if( user_id != null ){
			List<SchoolModel> schools = SchoolModel.me.getSchool();
			setAttr("schools", schools);
			UserModel userModel = UserModel.me.findById(user_id);
			setAttr("userModel", userModel);
		    render("info.html");
		}
	}
	
	public void help(){
		Integer user_id = getSessionAttr("userID");
		if( user_id != null ){
		    render("help.html");
		}
	}
	
	public void help_money(){
		Integer user_id = getSessionAttr("userID");
		if( user_id != null ){
		    render("help_money.html");
		}
	}
	
	public void help_print(){
		Integer user_id = getSessionAttr("userID");
		if( user_id != null ){
		    render("help_print.html");
		}
	}
	
	public void help_word_pdf(){
		Integer user_id = getSessionAttr("userID");
		if( user_id != null ){
		    render("help_word_pdf.html");
		}
	}
	
	public void help_instruction(){
		Integer user_id = getSessionAttr("userID");
		if( user_id != null ){
		    render("help_instruction.html");
		}
	}
	
	public void quit(){
		removeSessionAttr("user_phonenumber");
		removeSessionAttr("userID");
		removeCookie("bbsID");
		render("login.html");
	}
	
	public void test(){
		Integer user_id = getSessionAttr("userID");
		if( user_id != null ){
			UserModel userModel = UserModel.me.findById(user_id);
			setAttr("userModel", userModel);
		    render("test.html");
		}
	}

	public void upload(){
		Integer user_id = getSessionAttr("userID");
		String now_time = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss").format( new Date());
		UploadFile file = getFile("UpLoadFile","test_upload/"+Integer.toString(user_id)+ "/" + now_time+"/",10000000);
		String papertype = getPara("papertype");
		String papernum_str = getPara("papernum");
		Integer papernum = Integer.valueOf(papernum_str);
		String beizhu = getPara("intro");
		String submit_time = now_time;

//		File oldFile=new File(file.getSaveDirectory() + "/" + now_time + "/" + file.getFileName() );
//        File newFile=new File(file.getSaveDirectory() + "/" + "first_rename.pdf" );
        
//        System.out.println(file.getFileName());
//        boolean tag = oldFile.renameTo( newFile );
//		boolean tag = file.getFile().renameTo(new File( file.getSaveDirectory() + "/test_upload/first_rename.pdf"));
		//if( tag == true ){
		//	System.out.println("=============");
		//	oldFile.delete();
		//}
		
		//添加数据库,添加文件
		String filename = file.getSaveDirectory() + file.getFileName();
		PrintfileModel.me.updatePrintfile(user_id,file.getFileName(),filename);
		
		PrintfileModel savefileid = PrintfileModel.me.getFileid(user_id,file.getFileName(),file.getSaveDirectory() + file.getFileName());
		//添加数据库，添加任务
		Integer gold = papernum;
		Integer print_shop_id = Integer.valueOf(getPara("printshop"));
		Integer file_id = savefileid.getInt("file_id");
		TaskidModel task = new TaskidModel();
		task.set("name", file.getFileName());
		task.set("user_id", user_id);
		task.set("gold", gold);
		task.set("print_shop_id", print_shop_id);
		task.set("file_id", file_id);
		task.set("papertype", papertype);
		task.set("papernum", papernum);
		task.set("beizhu", beizhu);
		task.set("submit_time", submit_time);
		task.set("finish_flag", 0);
        //List<LeafletModel> list = LeafletModel.me.getAllLeaftel();
        setSessionAttr("task", task);
        
        //根据用户所在学校决定是否显示传单
		//获取未用过过的传单
        UserModel userModel = UserModel.me.findById(user_id);
		List<Integer> finish_leaflets = TaskidModel.me.getFinishLeaftel(user_id);
		//到选择传单页面
        List<LeafletModel> list = LeafletModel.me.getAllLeaftel_nofinish(finish_leaflets,userModel.getInt("school").toString(),gold);
        setAttr("leafletList", list);
		render("leafelt.html");


	//错误页面
	}
	
	//public void download() {
	//    renderFile(new File("./WebRoot/upload/2011年计算机文化基础试题.pdf"));
	    //render("upload.html");
	//}
	
	
	public void download() {
		PrintfileModel printfile = PrintfileModel.me.findById(getParaToInt());
		System.out.println(getParaToInt());
		String path = (String) printfile.get("path_yuan");
		System.out.println( path );
	    renderFile(new File(path));
	    //render("upload.html");
	}
	public void download_leaflet() {
		LeafletModel leaflet = LeafletModel.me.findById(getParaToInt());
		String path = (String) leaflet.get("path");
	    renderFile(new File(path));
	    //render("upload.html");
	}
	
	@ActionKey("/controller/sign")
	public void sign(){
		System.out.println( getPara("phonenumber"));
		//1.搜索数据库sign,是否存在当天
		String now_time = new SimpleDateFormat("yyyy-MM-dd").format( new Date());
		System.out.println( now_time);
		if (SignModel.me.getSignByNameAndDate(getPara("phonenumber"),now_time) == null) {
			System.out.println( "11111111111");
			//获取连续多少天登录
			//写入数据,今天也领取了金币
			SignModel.me.SignByNameAndDate(getPara("phonenumber"),now_time,1,"geted");
			//金币数量提交
			UserModel userModel = UserModel.me.findById(getSessionAttr("userID"));
			Integer gold_t = userModel.getInt("gold") + 1;
			userModel.set("gold", gold_t);
			userModel.update();
			//页面转换
			this.renderText( "获取金币"  );
		} else {
			this.renderText( "今天已签到"  );
		}
		//存在,则签名失败,已经签过了
		//不存在,则查询他的签到情况,计入签到多少金币
		
		
	}
	
	@ActionKey("/controller/verify")
	public void verify(){
		System.out.println( getPara("phonenumber"));
		String phonenumber = getPara("phonenumber");
		Boolean flag_time = false;
        //获取电话号码对应的验证码和时间
		if (UserModel.me.getUserByPhoneNumber(phonenumber)) {
			this.renderText( "号码已注册123"  );
			return;
		}
		YangzhengmaModel yanzhengmaModel = YangzhengmaModel.me.findByPN(phonenumber);
		if(yanzhengmaModel == null){
			flag_time = true;
		}else {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss");
			try {
				Date d = sdf.parse(yanzhengmaModel.getStr("time"));
				long lold = d.getTime();
				
				d = new Date();
				long lnew = d.getTime();
				
				if (lnew - lold > 60 * 1000) {
					flag_time = true;
				} else {
					flag_time = false;
				}
			} catch (ParseException e) {
				e.printStackTrace(); 
			}
		}
		if(flag_time){
			//生成随机数
			Integer x1=(int)(Math.random()*9);
			Integer x2=(int)(Math.random()*9);
			Integer x3=(int)(Math.random()*9);
			Integer x4=(int)(Math.random()*9);
			String yangzheng = x1.toString()+x2.toString()+x3.toString()+x4.toString();
			System.out.println(yangzheng);
			//发送短信
			String city = "suzhou";//参数
			String url = "http://v.juhe.cn/sms/send?mobile="+phonenumber+"&tpl_id=5685&tpl_value=%23code%23%3D"+yangzheng+"&key=5d53a4e1cbb182f03b7ab57b8ddcfb7f";//url为请求的api接口地址
			String charset ="UTF-8";
			String jsonResult = get(url, charset);
			
			//验证码存入数据库
			
			int flag = 0;
			if(yanzhengmaModel == null){
				flag = 1;
				yanzhengmaModel = new YangzhengmaModel();
			}
			yanzhengmaModel.set("phonenum", phonenumber);
			yanzhengmaModel.set("vcode",yangzheng);
			String now_time = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss").format( new Date());
			yanzhengmaModel.set("time",now_time);
			if(flag == 1){
				yanzhengmaModel.save();
			}
			else {
				yanzhengmaModel.update();
			}
			this.renderText( "发送成功"  );
		}
		else {
			this.renderText( "请等待1分钟之后再发"  );
		}
	}

	
	  public void choose_leaflet() {
	        // 获取表单域名为studentID的值
	        // Student.dao.deleteById(getPara("studentID"));
	        // 获取url请求中第一个值
		  Integer user_id = getSessionAttr("userID");
		  Integer leaflet_id = getParaToInt();
		  TaskidModel task = getSessionAttr("task");
		  task.set("leaflet_id", leaflet_id);
		  //判断金币是否够,不够则要提示
		  Integer consume_gold = task.getInt("papernum");
		  UserModel userModel = UserModel.me.findById(getSessionAttr("userID"));
		  Integer gold_t = userModel.getInt("gold") - consume_gold;
		  if(gold_t < 0){
			  setSessionAttr("money_enough_flag", 1);
			  redirect("/user/print");
			  return;
		  }
	      if (task.save()){
			    //如果任务提交成功,则修改用户的金币

				Integer use_gold_t = userModel.getInt("use_gold") + consume_gold;
				userModel.set("gold", gold_t);
				userModel.set("use_gold", use_gold_t);
				userModel.update();
				
				//传单的金额扣除
				LeafletModel leaflet = LeafletModel.me.findById(leaflet_id);
				leaflet.set("user_num", leaflet.getInt("user_num")+1);
				leaflet.set("paper_num", leaflet.getInt("paper_num")+task.getInt("papernum"));
				Integer use_gold_temp = leaflet.getInt("use_gold")+task.getInt("gold");
				leaflet.set("use_gold", use_gold_temp);
				leaflet.set("remainder_money", leaflet.getInt("gold_num")-use_gold_temp);
				leaflet.update();

	            //生成新文件
				try{
					String leaflet_path = leaflet.getStr("path");
					PrintfileModel printfile = PrintfileModel.me.findById(task.getInt("file_id"));
					System.out.println(leaflet_path);
					
				    PdfReader reader1 = new PdfReader(printfile.getStr("path_yuan"));
				    PdfReader reader2 = new PdfReader(leaflet_path);
				    System.out.println(printfile.getStr("path_yuan"));
				    
				    String now_time = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss").format( new Date());
				    //String path_new = "D:\\Workspace\\javaweb\\kuaiying\\WebRoot\\upload\\test_upload\\"+"shengcheng" + "\\" +Integer.toString(user_id)+ "\\" + now_time+"\\"+printfile.getStr("name");
				    //String path_new = "D:\\Workspace\\javaweb\\kuaiying\\WebRoot\\upload\\test_upload\\"+"shengcheng" + "\\" +Integer.toString(user_id)+ "_" + now_time+"_"+printfile.getStr("name");
				    String path_new = "/opt/tomcat/webapps/kuaiying/upload/test_upload/"+"shengcheng" + "/" +Integer.toString(user_id)+ "_" + now_time+"_"+printfile.getStr("name");
				    System.out.println("path_new");
				    System.out.println(path_new);
				    printfile.set("path_new", path_new);
				    printfile.update();
				    
				    
				    FileOutputStream out = new FileOutputStream(path_new);
				     
				    Document document = new Document();
				    PdfWriter writer = PdfWriter.getInstance(document, out);
				     
				    document.open();
				    PdfContentByte cb = writer.getDirectContent();
				     
				    int totalPages = 0;
				    totalPages += reader1.getNumberOfPages();
				    //totalPages += reader2.getNumberOfPages();
				     
				    java.util.List<PdfReader> readers = new ArrayList<PdfReader>();
				    readers.add(reader1);
				    //readers.add(reader2);
				     
				    int pageOfCurrentReaderPDF = 0;
				    Iterator<PdfReader> iteratorPDFReader = readers.iterator();
				     
				    // Loop through the PDF files and add to the output.
				    while (iteratorPDFReader.hasNext()) {
				        PdfReader pdfReader = iteratorPDFReader.next();
				     
				        // Create a new page in the target for each source page.
				        while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
				            document.newPage();
				            pageOfCurrentReaderPDF++;
				            PdfImportedPage page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
				            cb.addTemplate(page, 0, 0);
				            document.newPage();
				            PdfImportedPage page2 = writer.getImportedPage(reader2, (pageOfCurrentReaderPDF-1) % reader2.getNumberOfPages() + 1);
				            cb.addTemplate(page2, 0, 0);
				        }
				        pageOfCurrentReaderPDF = 0;
				    }
				    out.flush();
				    document.close();
				    out.close();
				}
				catch (Exception e){
					System.out.println(e);
				}
	            
				//到orderyemian
		        List<TaskidModel> list = TaskidModel.me.getAllTask_user(user_id);
		        setAttr("leafletList", list);
		        redirect("/user/order");
			}
		  
	    }
}
